package custom.security.browser.controller;

import custom.security.browser.support.RequireFailedResponse;
import custom.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证url请求是属于页面跳转还是访问API
 * 根据请求结尾是否为.html进行判断
 * Created by wgt on 2017/10/13.
 */
@Slf4j
@RestController
public class RequireUrlController {

    /**
     * 用户请求时的url，当需要身份验证时，跳转到验证请求（/authentication/require）时，会将原本请求的url缓存到session里
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     * Spring提供的请求跳转类
     */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 当用户请求需要身份验证时，跳转到该处
     * @param request
     * @param response
     * @return
     */
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    @RequestMapping(value = "/authentication/require")
    public RequireFailedResponse require(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //从session里获取到存入session的Request对象
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if (savedRequest!=null){

            //获取引发跳转的url
            String targetUrl = savedRequest.getRedirectUrl();
            log.info("the redirect request is cause by :{}",targetUrl);

            // 如果请求是html跳转请求，则跳转到html登陆页面，不是则返回json,响应401状态码
            if (StringUtils.endsWithIgnoreCase(targetUrl,".html")){
                redirectStrategy.sendRedirect(request,response,securityProperties.getBrowser().getLoginPage());
            }
        }


        return new RequireFailedResponse("This request requires authentication");
    }
}
